import {configureStore, combineReducers, createSlice} from '@reduxjs/toolkit';
import {persistReducer, persistStore} from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // 默认使用 localStorage

const authSlice = createSlice({
    name: 'auth',
    initialState: {
        token: null,
        user: null,
    },
    reducers: {
        setToken: (state, action) => {
            state.token = action.payload;
        },
        setUser: (state, action) => {
            state.user = action.payload;
        },
        logout: (state) => {
            state.token = null;
            // state.user = null;
        },
    },
});

export const {setToken, setUser, logout} = authSlice.actions;

const persistConfig = {
    key: 'root',
    storage,
    whitelist: ['auth'] // 你想要持久化的状态
};

// 使用 combineReducers 组合 reducers
const rootReducer = combineReducers({
    auth: authSlice.reducer,
});

// 使用 persistReducer 包装 rootReducer
const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: ['persist/PERSIST', 'persist/REHYDRATE', 'persist/REGISTER'],
            },
        }),
});

export const persistor = persistStore(store);

export default store;
